package com.cloud.force.api.handler;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 责任链模式
 * 
 * @author taominglong
 *
 */
public class HandlerChain implements ApplicationContextAware {
	protected ApplicationContext applicationContext;

	private int index = 0;

	private List<Handler> handlers = new ArrayList<Handler>();

	public HandlerChain addHandler(Handler handler) {
		this.handlers.add(handler);
		return this;
	}

	public void doHandler(Request request, Response resp) {
		if (index == handlers.size())
			return;
		Handler handler = handlers.get(index++);
		handler.handler(request, resp, this);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}
}
